package fragment;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.example.menhoo.toollibrary.common.helper.AndroidFileUtil;
import com.example.menhoo.toollibrary.common.helper.DateUtil;
import com.example.menhoo.toollibrary.common.helper.MessageUtil;
import com.example.menhoo.toollibrary.common.utils.FileUtil;
import com.example.menhoo.toollibrary.common.utils.HandlerUtil;
import com.example.menhoo.toollibrary.common.utils.NumberUtil;
import com.example.menhoo.toollibrary.common.utils.VibrateUtil;
import com.lidroid.xutils.exception.DbException;
import com.lidroid.xutils.util.LogUtils;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import app.MyDownload;
import application.AppApplication;
import mainUI.AppFragment;
import menhoo.com.i8officelibrary.R;
import model.DownloadDbModel;

/**
 * 下载已经完成
 * Created by yanglei on 15/11/12.
 */
public class DownloadList extends AppFragment {
    /**
     * 是否进入编辑状态
     */
    public boolean F = false;

    SwipeRefreshLayout swipeLayout;

    ListView listView;

    LinearLayout toolbarBottom;

    RelativeLayout toolbarTop;

    Button buttonCancel;

    Button buttonSelectAll;

    Button buttonDelete;

    TextView textViewEditTitle;

    DownloadAdapter adapter;

    Map<String, View> map = new HashMap();

    @Override
    public boolean onBackPressed() {
        return false;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContextView(R.layout.fragment_download_list);
    }

    @Override
    public void init() {
        super.init();
        //
        try{
            swipeLayout = (SwipeRefreshLayout)rootView.findViewById(R.id.swipeLayout);
            listView = (ListView)rootView.findViewById(R.id.listView);
            toolbarBottom = (LinearLayout)rootView.findViewById(R.id.toolbarBottom);
            toolbarTop = (RelativeLayout)rootView.findViewById(R.id.toolbarTop);
            buttonCancel = (Button)rootView.findViewById(R.id.buttonCancel);
            buttonSelectAll = (Button)rootView.findViewById(R.id.buttonSelectAll);

            buttonDelete = (Button)rootView.findViewById(R.id.buttonDelete);
            textViewEditTitle = (TextView)rootView.findViewById(R.id.textViewEditTitle);

            buttonCancel.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    hideToolBar();
                }
            });

            buttonSelectAll.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(adapter!=null){
                        adapter.SelectAll();
                    }
                }
            });

            buttonDelete.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(adapter==null) return;

                    List<DownloadDbModel> removeList = new ArrayList<>();
                    List<String> listUrl = adapter.getSelectUrl();

                    if(listUrl==null || listUrl.size()==0){
                        MessageUtil.showShortToast(context,"请选择删除项");
                        return;
                    }

                    for(String url : listUrl){

                        try {
                            DownloadDbModel downloadDbModel = adapter.getItem(url);
                            File deleteFile = new File(downloadDbModel.path);
                            if(deleteFile.exists()){
                                FileUtil.deleteFile(deleteFile);
                            }
                            removeList.add(downloadDbModel);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if(removeList.size()>0){
                        adapter.remove(removeList);
                        try {
                            getDB().deleteAll(removeList);

                        } catch (DbException e) {
                            e.printStackTrace();
                        }
                        adapter.notifyDataSetChanged();
                    }
                    if(adapter.getData().size()==0){
                        hideToolBar();
                        getData();
                    }
                    try {
                        MyDownload myDownload = (MyDownload) getAppActivity();
                        if (myDownload != null) {
                            myDownload.refreshSdCurrSize();
                        }
                    } catch (Exception e) {
                        LogUtils.e(e.getMessage() + "");
                    }
                }
            });

        }
        catch (Exception e){
            LogUtils.e(e.getMessage()+"");
        }


        setTitleDisplay(false);
        hideToolBar();
        SwipeRefreshLayout.OnRefreshListener listener = new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                getData();
            }
        };
        swipeLayout.setOnRefreshListener(listener);
        swipeLayout.post(new Runnable() {
            @Override
            public void run() {
                swipeLayout.setRefreshing(true);
            }
        });
        listener.onRefresh();
    }

    /**
     * 得到数据
     */
    void getData() {
        hideAll();
        new Thread(new Runnable() {
            @Override
            public void run() {
                Date startTime = new Date();
                try {
                    final List<DownloadDbModel> list = AppApplication.getDownloadFiles();
                    if(list!=null && list.size()>0){
                        HandlerUtil.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                adapter = new DownloadAdapter(list);
                                listView.setAdapter(adapter);
                                swipeLayout.setRefreshing(false);
                            }
                        });
                    }
                    else{
                        HandlerUtil.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                showEmpty();
                            }
                        });
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    LogUtils.e(e.getMessage() + "");
                }

                Date endTime = new Date();
                if (endTime.getTime() - startTime.getTime() < 1000) {
                    try {
                        Thread.sleep(1000 - (endTime.getTime() - startTime.getTime()));
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                HandlerUtil.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        swipeLayout.setRefreshing(false);
                    }
                });

            }
        }).start();
    }

    private void showToolBar() {
        toolbarTop.setVisibility(View.VISIBLE);
        toolbarBottom.setVisibility(View.VISIBLE);
        swipeLayout.setEnabled(false);
        F = true;
        if (adapter != null) {
            adapter.notifyDataSetChanged();
        }
    }

    public void hideToolBar() {
        toolbarTop.setVisibility(View.GONE);
        toolbarBottom.setVisibility(View.GONE);
        swipeLayout.setEnabled(true);
        F = false;
        if (adapter != null) {
            adapter.clearSelect();
        }
    }



    class DownloadAdapter extends BaseAdapter {
        List<DownloadDbModel> data = null;

        public DownloadAdapter() {
            this.data = new ArrayList<DownloadDbModel>();
        }

        public DownloadAdapter(List<DownloadDbModel> data) {
            this.data = data;
        }

        public void add(List<DownloadDbModel> data) {
            if (this.data != null) {
                this.data.addAll(data);
                notifyDataSetChanged();
            }
        }

        @Override
        public int getCount() {
            if (this.data != null) {
                return this.data.size();
            } else {
                return 0;
            }

        }


        @Override
        public DownloadDbModel getItem(int position) {
            if (this.data != null) {
                return this.data.get(position);
            } else {
                return null;
            }

        }

        public List<DownloadDbModel> getData(){
            return this.data;
        }
        public void remove(List<DownloadDbModel> list){
            for(DownloadDbModel item : list){
                if(map.containsKey(item.url)){
                    map.remove(item.url);
                }
            }
            this.getData().removeAll(list);
        }
        public DownloadDbModel getItem(String url) {
            if (this.data != null) {
                for (DownloadDbModel item : data) {
                    if (item.url.equalsIgnoreCase(url)) {
                        return item;
                    }
                }
                return null;
            } else {
                return null;
            }

        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        public void clearSelect() {
            for (View v : map.values()) {
                v.setTag(R.id.checkBox, false);
            }
            notifyDataSetChanged();
        }

        public void SelectAll() {
            for (View v : map.values()) {
                v.setTag(R.id.checkBox, true);
            }
            notifyDataSetChanged();
        }

        public List<String> getSelectUrl() {
            List<String> list = new ArrayList<>();
            for (String url : map.keySet()) {
                View v = map.get(url);
                boolean isSelect = (boolean) v.getTag(R.id.checkBox);
                if (isSelect) {
                    list.add(url);
                }
            }
            return list.size() > 0 ? list : null;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            final DownloadDbModel model = getItem(position);
            ViewHolder viewHolder = null;
            if (map.containsKey(model.url)) {
                convertView = map.get(model.url);
                viewHolder = (ViewHolder) convertView.getTag();
            } else {
                convertView = getLayoutInflater().inflate(R.layout.fragment_download_list_item, null);
                viewHolder = new ViewHolder();
                viewHolder.imageView = (ImageView) convertView.findViewById(R.id.imageView);
                viewHolder.imageViewCheck = (ImageView) convertView.findViewById(R.id.imageViewCheck);
                viewHolder.textView = (TextView) convertView.findViewById(R.id.textView);
                viewHolder.textViewSize = (TextView) convertView.findViewById(R.id.textViewSize);
                viewHolder.textViewTime = (TextView) convertView.findViewById(R.id.textViewTime);
                viewHolder.linearLayoutCheck = (LinearLayout) convertView.findViewById(R.id.linearLayoutCheck);
                convertView.setTag(viewHolder);
                convertView.setTag(R.id.checkBox, false);
                convertView.setTag(R.id.query, model.path);
                map.put(model.url, convertView);
            }

            viewHolder.imageView.setImageResource(AndroidFileUtil.getFileIconRID(model.name));

            if (F) {
                viewHolder.linearLayoutCheck.setVisibility(View.VISIBLE);
                //恢复选中状态
                boolean isSelect = (boolean) convertView.getTag(R.id.checkBox);
                if (isSelect) {
                    viewHolder.imageViewCheck.setImageResource(R.drawable.abc_btn_check_to_on_mtrl_015);
                } else {
                    viewHolder.imageViewCheck.setImageResource(R.drawable.abc_btn_check_to_on_mtrl_000);
                }
            } else {
                viewHolder.linearLayoutCheck.setVisibility(View.GONE);
            }

            viewHolder.textView.setText(model.name);
            viewHolder.textViewSize.setText(NumberUtil.getFileSize_KB_MB_GB(model.size));
            viewHolder.textViewTime.setText(DateUtil.DateToString(model.updateTime,DateUtil.TimeFormatOne2));

            convertView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (F) {
                        boolean oldSelect = (boolean) v.getTag(R.id.checkBox);
                        boolean newSelect = !oldSelect;
                        v.setTag(R.id.checkBox, newSelect);
                        ImageView imageViewCheck = (ImageView) v.findViewById(R.id.imageViewCheck);
                        if (newSelect) {
                            imageViewCheck.setImageResource(R.drawable.abc_btn_check_to_on_mtrl_015);
                        } else {
                            imageViewCheck.setImageResource(R.drawable.abc_btn_check_to_on_mtrl_000);
                        }
                        List<String> list = getSelectUrl();
                        textViewEditTitle.setText("已选中" + (list != null ? list.size() : 0) + "项");
                    } else {
                        try {
                            //打开文件
                            String path = (String) v.getTag(R.id.query);
                            startActivity(AndroidFileUtil.openFile(path));
                        } catch (Exception e) {
                            LogUtils.e(e.getMessage() + "");
                        }

                    }

                }
            });
            convertView.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    VibrateUtil.vibrateShot(context);
                    v.setTag(R.id.checkBox, true);
                    List<String> list = getSelectUrl();
                    textViewEditTitle.setText("已选中" + (list != null ? list.size() : 0) + "项");
                    showToolBar();
                    return false;
                }
            });

            return convertView;
        }

    }

    class ViewHolder {
        ImageView imageView, imageViewCheck;
        TextView textView,textViewSize,textViewTime;
        LinearLayout linearLayoutCheck;
    }
}
